﻿package com.sff.manager {
	
	import com.sff.core.IFont;
	import com.sff.core.sff_internal;
	import com.sff.style.AdvanceStyleSheet;
	import com.sff.style.CssStyle;
	
	import flash.display.DisplayObject;
	import flash.text.Font;
	import flash.utils.Dictionary;
	
	/**
	 * TODO:
	 * - inherit styles from parent?
	 * - inherit fonts from parent?
	 */ 
	
	public class StyleManager {
		
		protected var dicStyle	:Dictionary;
		protected var dicFont	:Dictionary;
		
		public function StyleManager() {
			dicStyle = new Dictionary();
			dicFont = new Dictionary();
		}	
		
		public function parseCssStyleSheet(str:String):void {			
			//create all CssStyle from style sheet
			var ass:AdvanceStyleSheet = new AdvanceStyleSheet();
			ass.parseCSS(str);
			
			//store all CssStyle in StyleManager class
			var arrStyle:Array = ass.sff_internal::getStyles();		
			var style:CssStyle;
			
			for (var i:int = 0; i < arrStyle.length; i ++) {
				style = arrStyle[i];
				setStyle(style.selector, style);
			}	
		}
		
		public function setStyle(selector:String, cssStyle:CssStyle):void {
			selector = selector.toLowerCase();
			
			if (dicStyle[selector] == null || dicStyle[selector] == undefined) {			
				dicStyle[selector.toLowerCase()] = cssStyle;
			} else {
				
				//if it contains selector, then mixed them together with new priority
				var oldStyle:CssStyle = dicStyle[selector];				
				var dicTemp:Dictionary = oldStyle.sff_internal::properties;
				
				for (var key:String in dicTemp) {					
					if (cssStyle.hasProperty(key) == false) {						
						cssStyle.setProperty(key, dicTemp[key]);
					}	
				}
				
				dicStyle[selector] = cssStyle;
			}
		}
		
		public function getStyle(selector:String): CssStyle {
			return dicStyle[selector.toLowerCase()];
		}
		
		public function applyStyle(target:DisplayObject, selector:String):void {
			var style:CssStyle = dicStyle[selector.toLowerCase()];
			if (style) {
				
				var fontFamily:String = style.getProperty('fontFamily') as String;				
				if (!dicFont[fontFamily]) {
					style.format(target, false);	
				} else {
					style.format(target);
				}
			}
		}
		
		public function clearStyle(selector:String):void {
			selector = selector.toLowerCase();
			
			var style:CssStyle = dicStyle[selector];
			if (style) {
				delete dicStyle[selector];				
				dicStyle[selector] = null;				
			}			
		}
		
		public function addFont(font:IFont):void {			
			if (font && font.fontClass) {
			
				//register font 
				Font.registerFont(font.fontClass);				
			
				//store font to check before applyStyle
				var cls:Font = new font.fontClass();				
				dicFont[cls.fontName] = cls;
			}			
		}
	}
}